import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tiktokadult/hj_page/user_center_page/model/liabrary_config_model.dart';
import 'package:tiktokadult/hj_utils/widget_utils.dart';

class VideoLibrayHeader extends StatefulWidget {
  final Function(Map<String, dynamic> filter) filtersOnchanged;
  final List<List<PayType>?> dataSource;
  final Map<String, dynamic> filterMap;

  VideoLibrayHeader(this.dataSource, {super.key, required this.filterMap, required this.filtersOnchanged});

  @override
  State<VideoLibrayHeader> createState() => _VideoLibrayHeaderState();
}

class _VideoLibrayHeaderState extends State<VideoLibrayHeader> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(top: 0, left: 16, right: 0),
      child: Column(
        children: widget.dataSource.map((e) {
          if (e == null) return SizedBox.shrink();
          return Container(
            width: double.infinity,
            height: 40,
            padding: EdgeInsets.only(top: 12),
            child: ListView.separated(
              itemCount: e.length + 1,
              scrollDirection: Axis.horizontal,
              separatorBuilder: (ctx, index) => index == 0 ? 24.sizeBoxW : SizedBox.shrink(),
              itemBuilder: (BuildContext context, int index) {
                final type = index == 0 ? e.first : e[index - 1];
                bool isSelected;

                isSelected = widget.filterMap[type.type ?? ''] == type;

                if (index == 0)
                  return Container(
                    alignment: Alignment.center,
                    child: Text(
                      type.title ?? '',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 16.sp,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  );
                return InkWell(
                  child: Container(
                    alignment: Alignment.center,
                    padding: EdgeInsets.symmetric(horizontal: 12),
                    child: Text(
                      type.name ?? '',
                      style: TextStyle(
                          color: isSelected ? Color(0xff00D6BE) : Colors.white.withOpacity(.6),
                          fontSize: isSelected ? 16.sp : 16.sp,
                          fontWeight: isSelected ? FontWeight.w500 : FontWeight.w400),
                    ),
                  ),
                  onTap: () {
                    widget.filterMap[type.type ?? ''] = type;
                    widget.filtersOnchanged(widget.filterMap);
                    setState(() {});
                  },
                );
              },
            ),
          );
        }).toList(),
      ),
    );
  }
}

class VideoLibrayPinHeader extends StatefulWidget {
  final Map<String, dynamic> filterMap;
  final List<List<PayType>?> dataSource;
  final Function(Map<String, dynamic> filter) filtersOnchanged;

  VideoLibrayPinHeader(this.filterMap, {super.key, required this.dataSource, required this.filtersOnchanged});

  @override
  State<VideoLibrayPinHeader> createState() => _VideoLibrayPinHeaderState();
}

class _VideoLibrayPinHeaderState extends State<VideoLibrayPinHeader> with SingleTickerProviderStateMixin {
  late Animation<double> _animation;
  late AnimationController _controller;
  bool showMask = false;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(duration: const Duration(milliseconds: 200), vsync: this)
      ..addListener(() {
        if (_controller.isCompleted) {
          showMask = true;
        } else if (_controller.isDismissed) {
          showMask = false;
        }
        setState(() {});
      });

    //使用自定义曲线动画过渡效果
    _animation = CurvedAnimation(parent: _controller, curve: Curves.linear);
  }

  String generateFilterString() {
    String filterS = '';
    filterS = widget.filterMap
        .map((key, value) {
          // if (key == 'tags') return MapEntry(key, (value as List?)?.map((e) => e.name).join('.'));
          return MapEntry(key, value.name);
        })
        .values
        .join('.');

    if (filterS.startsWith('.')) return filterS.substring(1);
    return filterS;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        InkWell(
          child: Container(
              height: 42,
              width: double.infinity,
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(horizontal: 16),
              decoration: BoxDecoration(color: Colors.black.withOpacity(.8)),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  ConstrainedBox(
                    constraints: BoxConstraints(maxWidth: double.infinity),
                    child: Text(
                      generateFilterString(),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.white.withOpacity(.8), fontSize: 14),
                    ),
                  ),
                  4.sizeBoxW,
                  AnimatedBuilder(
                    animation: _animation,
                    builder: (ctx, child) => Transform.rotate(
                      angle: pi * _animation.value,
                      child: Icon(
                        Icons.arrow_drop_down,
                        size: 22,
                        color: Colors.white.withOpacity(.6),
                      ),
                    ),
                  )
                ],
              )),
          onTap: () {
            if (_controller.isCompleted)
              _controller.reverse();
            else
              _controller.forward();
          },
        ),
        SizeTransition(
            sizeFactor: _animation,
            child: Container(
              color: Color(0xff11111A),
              child: Column(
                children: [
                  Padding(
                    padding: EdgeInsets.symmetric(
                      horizontal: 16,
                    ),
                    child: VideoLibrayHeader(
                      widget.dataSource,
                      filterMap: widget.filterMap,
                      filtersOnchanged: (filter) {
                        widget.filtersOnchanged(filter);
                        _controller.reverse();
                        setState(() {});
                      },
                    ),
                  ),
                  12.sizeBoxH,
                ],
              ),
              // color: Color(0xff181824),
            )),
        if (showMask)
          Expanded(
            child: InkWell(
              child: Container(),
              onTap: () => _controller.reverse(),
            ),
          )
      ],
    );
  }
}
